<?php
/**
 * Created by IntelliJ IDEA.
 * User: HXL
 * Date: 2018/5/7
 * Time: 17:25
 */
namespace app\order\controller;

use app\order\model\Admins;
use app\order\model\Clients;
use app\order\model\Fittings;
use app\order\model\Logs;
use app\order\model\Manufacturer;
use app\order\model\MeterTypes;
use app\order\model\ModelSupplies;
use app\order\model\ModelTypes;
use app\order\model\Orderexec;
use app\order\model\OrderMeters;
use app\order\model\Orders;
use app\order\model\ProductPrinciple;
use app\order\model\Programs;
use app\order\model\States;
use app\order\model\Supplies;
use think\Controller;
use think\Db;
use app\order\crypt\AesCrypt;
use app\order\model\Roles;
use app\order\model\Ways;
use app\order\model\Depts;
use think\Lang;
use think\Response;
use app\order\sms\Sms;

class Base extends Controller{
    public function _initialize(){
        $username = session('order_user');
        $status = session('order_status');
        $surname = session('order_surname');
        $sale_id = session('order_saleid');
        $a = is_null($username);
        //var_dump($a);exit();
        //判断用户是否已经登录
        if ($a) {
            return $this->redirect('Login/index');
        }
        $this->assign("username", $username);
        $this->assign("surname", $surname);
        $this->assign("status", $status);
//        $this->assign("sale_id", $sale_id);
        //登录成功，将用户的权限操作id传给前端
        $this->assignOwnWays($username);
        return true;
    }

    public function authVerify(){
        $controller = ucfirst(request()->controller());
        $action = request()->action();
        $auth = $this->auth($controller, $action);
        if(!$auth){
            return $this->error(Lang::get('no authority'));
        }
    }
    /**
     * 1表示有权限，0表示无权限
     */
    public function auth($controller, $action){
        $username = session('order_user');
        $ways = $this->getWaysByUid($username);
        $uth = $controller.'/'.$action;
        if(in_array($uth, $ways)){
            return 1;
        }
        return 0;
    }

    /*{if condition="in_array('Role',$ownways['w_control']) && in_array('add',$ownways['w_way'])"}*/
    /**
     * 根据UID获取该用户所有权限(url地址)
     * @param $uid
     * @return array|int
     */
    public function getWaysByUid($username){
        $find = $this->admins()->findById(array('username'=>$username));
        $role_id = $find['role_id'];
        $wid = $this->roles()->findById(array('role_id'=>$role_id));
        //查看是否有权限
        $len = strlen($wid['wid']);
        $control = array();
        $method = array();
        $url = array();
        if($len > 0){
            //去除最后一个','
            $wid['wid'] = substr($wid['wid'], 0, strlen($wid['wid'])-1);
            $widArr = explode(',', $wid['wid']);
            for($i=0;$i<count($widArr);$i++){
                $wid = $widArr[$i];
                $findWay = $this->ways()->findById(array('wid'=>$wid));
                $url[$i] = $findWay['url'];
            }
        }
        return $url;
    }
    protected function assignOwnWays($username){
        $ways = $this->getWaysByUid($username);
        //var_dump($ways);exit();
        if($ways == null){
            return $this->error(Lang::get('no authority'), 'Login/index');
        }else{
            $this->assign('ownways', $ways);
        }

    }
    /**
     * 输出返回数据
     * @access protected
     * @param mixed     $data 要返回的数据
     * @param String    $type 返回类型 JSON XML
     * @param integer   $code HTTP状态码
     * @return Response
     */
    protected function response($data, $type = 'json', $code = 200)
    {
        return Response::create($data, $type)->code($code);
    }

    ///////////展现option选项
    protected function asgDepts(){
        $field = 'de_id,dept_name,description,create_time_d';
        $where = '';
        $depts = $this->depts()->select($field, $where);
        $this->assign('depts', $depts);
    }

    protected function asWays(){
        $field = 'wid,w_name,pid,w_control,w_way,url,create_time,status';
        $where = '';
        $ways = $this->ways()->select($field, $where);
        $this->assign('ways', $ways);
    }

    protected function asgRoles(){
        $field = 'role_id,role_name,remark,create_time,wid,status';
        $where = '';
        $roles = $this->roles()->select($field, $where);
        $this->assign('roles', $roles);
    }

    protected function asgMeterTypes(){
        $field = 'meter_id,meter_type,caliber,create_time';
        $where = '';
        $meterTypes = $this->meterTypes()->select($field, $where);
        $this->assign('meterTypes', $meterTypes);
    }
    protected function asgModelTypes(){
        $field = 'model_id,model_type,create_time';
        $where = '';
        $modelTypes = $this->modelTypes()->select($field, $where);
        $this->assign('modelTypes', $modelTypes);
    }
    protected function asgPrincs(){
        $field = 'pid,product_principle,position,create_time';
        $where = '';
        $principles = $this->principles()->select($field, $where);
        $this->assign('principles', $principles);
    }
    protected function asgPros(){
        $field = 'pro_id,pro_name,create_time';
        $where = '';
        $programs = $this->programs()->select($field, $where);
        $this->assign('programs', $programs);
    }
    protected function asgFits(){
        $field = 'fid,fitting,pid,create_time';
        $where = '';
        $fittings = $this->fittings()->select($field, $where);
        $this->assign('fittings', $fittings);
        $this->assign('jsonfittings', json_encode($fittings));
    }
    protected function asgStates(){
        $field = 'sid,state';
        $where = '';
        $states = $this->states()->select($field, $where);
        $this->assign('states', $states);
    }
    protected function asgManus(){
        $field = 'mf_id,manufacturer';
        $where = '';
        $data = $this->manus()->select($field, $where);
        $this->assign('manus', $data);
    }
    protected function asgClients(){
        $table = 'states';
        $param = 'sid';
        $where = '';
        $clients = $this->clients()->join($table, $param, $where);
        //var_dump($clients);exit();
        $this->assign('clients', $clients);
    }

    /**
     * 订单评审
     */
    protected function asgOrders(){
        $field = "oid,parent_id,cid,client_contacts,order_placer,placer_phone,transport,meter_id,meter_len,order_qty,pro_id,fid,fid_num,is_valve,is_sieve,nameplate,is_mark,chain,is_infrade,measure_mode,alarm,overdraft,timezone,crypt,sgc,cry_utk,soft_from,other,create_time,deliver_status";
        $where = array('parent_id'=>0);
        //只显示主表订单
        $orders = $this->orders()->select($field, $where);
        $orderControl = new Order();
        $orders = $orderControl->resetOrders($orders);

        $this->assign('orders', $orders);
    }

    ///////model类
    protected function admins(){
        $admins = new Admins();
        return $admins;
    }
    protected function hex(){
        $hex = new AesCrypt();
        return $hex;
    }

    protected function meterTypes(){
        $meterTypes = new MeterTypes();
        return $meterTypes;
    }
    protected function modelTypes(){
        $modelTypes = new ModelTypes();
        return $modelTypes;
    }
    protected function orders(){
        $orders = new Orders();
        return $orders;
    }
    protected function orderexecs(){
        $execorders = new Orderexec();
        return $execorders;
    }
    protected function principles(){
        $principles = new ProductPrinciple();
        return $principles;
    }

    protected function roles(){
        $roles = new Roles();
        return $roles;
    }
    protected function ways(){
        $ways = new Ways();
        return $ways;
    }
    protected function depts(){
        $depts = new Depts();
        return $depts;
    }

    protected function fittings(){
        $fitting = new Fittings();
        return $fitting;
    }

    protected function programs(){
        $program =  new Programs();
        return $program;
    }
    protected function logs(){
        $logs = new Logs();
        return $logs;
    }

    protected function clients(){
        $clients = new Clients();
        return $clients;
    }

    protected function states(){
        $states = new States();
        return $states;
    }
    protected function manus(){
        $manus = new Manufacturer();
        return $manus;
    }
    protected function orderMeters(){
        $orderMeters = new OrderMeters();
        return $orderMeters;
    }
    protected function supplies(){
        $supplies = new Supplies();
        return $supplies;
    }
    protected function modelSupplies(){
        $modelSupplies = new ModelSupplies();
        return $modelSupplies;
    }
    /**
     * 分页
     * @param $table
     */
    public function page($table){
        $page = $table->render();
//        $currentPage = $table->currentPage();
//        $this->assign('currentPage', $currentPage);
//        $this->assign('pageOrder', ($currentPage-1)*10);
        $this->assign('page', $page);
    }


    /*
      *修改密码
      * */
    public function upass(){
        $username = session('order_user');
        //$this->assign('username', $username);
        $where = array('username'=>$username);
        $admin = Db::table('ari_admins')->where($where)->find();
        if (!$admin){
            return $this->error(Lang::get('no user exist'));
        }
        //var_dump($admin['password']);exit();
        $this->assign('uid', $admin['uid']);
        $string = new AesCrypt();
        //解密
        $password = $admin['password'];
        //var_dump($password);exit();
        $inputPassword = $string->encrypt(input('param.password'));
        $update = $string->encrypt(input('param.update'));
        $confirm = $string->encrypt(input('param.confirm'));
        if($password != $inputPassword){
            return $this->error(Lang::get('pass wrong'));
        }
        if ($update == $password){
            return $this->error(Lang::get('same to old'));
        }
        if ($update == ''){
            return $this->error(Lang::get('unallowed as null'));
        }
        if ($update != $confirm){
            return $this->error(Lang::get('two not same'));
        }
        $result = Db::table('ari_admins')->where('username', $username)->update(['password'=>$update]);
        //var_dump($result);exit();
        if (!$result){
            return $this->error(Lang::get('edit fail'));
        }
        session('order_user', null);
        return $this->success(Lang::get('edit success'), 'Login/index');

    }

    /**
     * 腾讯云短信接口
     */
    public function test(){
        $nationCode = '86';
        $phone = '18642881168';
        //模板参数
        $num = '1234基表';
        $status = '待组装';
        $result = Sms::sends($phone, $num, $status);
        /*
         * object(stdClass)#18 (5) { ["result"]=> int(0) ["errmsg"]=> string(2) "OK" ["ext"]=> string(0) ""
         *  ["sid"]=> string(29) "8:txRbOoog5O4hArDeJFf20180711" ["fee"]=> int(1) }
         *
         * */
        var_dump($result);exit();
    }

    ///////////////////////////公用方法
    /**
     * 是与否的显示
     * @param $is
     * @return string
     */
    public function isOrNo($is){
        switch ($is){
            case 0:
                $result = '否';
                break;
            case 1:
                $result = '是';
                break;
            default:
                $result = '不知道';
                break;
        }
        return $result;
    }

    /**
     * 红外开关，开启或关闭状态
     * @param $isInfrade
     * @return string
     */
    public function onOrOff($isInfrade){
        switch ($isInfrade){
            case 0:
                $result = '关闭';
                break;
            case 1:
                $result = '开启';
                break;
            default:
                $result = '关闭';
                break;
        }
        return $result;
    }

    /**
     * 订单状态（生产状态）
     * @param $isStatus
     * @return string
     */
    public function getStatus($isStatus){
        switch ($isStatus){
            case 0:
                $status = '已完成';
                break;
            case 1:
                $status = '生产中';
                break;
            case 2:
                $status = '未下单';
                break;
            case 3:
                $status = '待组装';
                break;
            case 4:
                $status = '组装中';
                break;
            default:
                $status = '';
                break;
        }
        return $status;
    }

    /**
     * 带逗号的字符串转数组
     * @param $string
     * @return bool|string
     */
    public function stringToArr($string){
        $arr = array();
        if(strlen($string) == 0){
            return $arr;
        }
        //1.字符串去除最后一个','
        $string = substr($string, 0, strlen($string)-1);
        //2.转换成数组，重组
        $arr = explode(',', $string);
        return $arr;
    }
    /**
     * 业务部门
     */
    public function setSaleDepts($saleId){
        switch ($saleId){
            case 1:
                $sale = '业务一部';
                break;
            case 2:
                $sale = '业务二部';
                break;
            case 3:
                $sale = '业务三部';
                break;
            case 4:
                $sale = '业务四部';
                break;
            default:
                $sale = '';
                break;
        }
        return $sale;
    }

    /**
     * 数组key按顺序排列
     * @param $arr
     * @return array
     */
    public function sortArr($arr){
        $len = count($arr);
        if($len > 0){
            $newArr = array();
            foreach ($arr as $value){
                $newArr[] = $value;
            }
            return $newArr;
        }
        return $arr;
    }

    /**
     * 获取数组中值最大的key和value
     * @param $arr
     * @return mixed
     */
    public function getMaxKeyV($arr){
        $key = null;
        $len = count($arr);
        $tmp = null;
        if($len > 1){
            for($i=0;$i<count($arr)-1;$i++){
                if($arr[$i] < $arr[$i+1]){
                    $tmp = $arr[$i+1];
                    $key = $i+1;
                }else{
                    $key = $i;
                    $tmp = $arr[$i];
                }
            }
            $res = $key.','.$tmp.',';
            $result = $this->stringToArr($res);
        }else if($len == 1){
            $result = $this->stringToArr('0'.','.$arr['0'].',');
        }else{
            $result = array();
        }
        return $result;
    }

    /**
     * 排序二维数组（for graphymeter）
     * @param $arr
     */
    public function assortArr($arr){
        $len = count($arr);
        if($len > 0){
            for($i=0;$i<$len;$i++){
                $assortKey[$i] = $len[$i]['meter_type'];
            }
            array_multisort($assortKey, SORT_ASC, $arr);
        }
        return $arr;
    }

}